package com.kkd.kkdapp.activity;

import java.util.List;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.Notify.Const;
import com.kkd.kkdapp.Notify.NotifyDispatcher;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.KkdAppInfo;
import com.kkd.kkdapp.db.app.model.Notice;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.fragment.FindFragment;
import com.kkd.kkdapp.fragment.IndexFragment;
import com.kkd.kkdapp.fragment.WalletFragment;
import com.kkd.kkdapp.http.entity.AllConfig;
import com.kkd.kkdapp.http.entity.HomePageData;
import com.kkd.kkdapp.http.entity.HomePageDataList;
import com.kkd.kkdapp.http.entity.HomePageNotice;
import com.kkd.kkdapp.http.entity.Regtips;
import com.kkd.kkdapp.http.entity.UpdateData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.UpdateApkManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

/**
 * 主页Acivity
 * 
 * @author mty
 */
public class HomeActivity extends BaseActivity implements OnClickListener {

	private final int ACCOUT_LOGIN_CODE = 101; // 账户跳转登录的请求码
	private final static int HAVE_NEW_APP = 1001;
	private final static int HAVE_NOTICE = 2;
	private final static int GET_HOMEPAGE_FAILURE = 3;
	private final static int GET_ALLCONFIG_SUCCESS = 4;
	private final static int CLICK_DELAY = 5;
	private boolean isFirstToCurrent = true;
	private boolean isFirstToWallet = true;
	private LinearLayout regular_bt; // 定期
	private ImageView regular_img;
	private TextView regular_tv;
	private RelativeLayout find_bt; // 发现
	private ImageView find_img;
	private TextView find_tv;
	private RelativeLayout wallet_bt; // 钱包
	private ImageView wallet_img;
	private ImageView home_bg_img;
	private TextView wallet_tv;
	private long mExitTime;
	private int versionId;
	public TextView dot;
	public TextView find_dot;
	private Dialog mDialog;
	private int time = 1;
	// private long createTime;
	// private String noticeDesc;
	// private String noticeTitle;
	UpdateApkManager mUpdateManager;
	private String upDesc;
	private String pageDesc;
	private TextView textView;
	FrameLayout mRegularFrameLayout;// 定期
	FrameLayout mCurrentFrameLayout;// 活期
	FrameLayout mFindFrameLayout;// 发现
	FrameLayout mWalletFrameLayout;// 钱包
	IndexFragment mRegularFragment = new IndexFragment();
	// CurrentFragment mCurrentFragment = new CurrentFragment();
	FindFragment mFindFragment = new FindFragment();
	WalletFragment mWalletFragment = new WalletFragment();
	// public HomePageNotice mHomePageNotice;
	private boolean navigationFlag = true;
	public AllConfig mAllConfig;
	public int curFragment = 0;
	private boolean isShowGuide = true;
	public static HomeActivity mActivity;
	private TextView tv1;
	private TextView tv2;
	private Regtips regtips;
	private ImageView iv_reg_reaward_image_forCache;
	private ImageView iv_poi_pre_reward_image_forCache;
	private ImageView iv_poi_pre_reward_image2_forCache;
	private ImageView iv_regSuccessImage_forCache;
	private ImageView iv_mis_succ_image_forCache;

	Handler mHandler = new Handler() {

		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HAVE_NEW_APP:
				String url = msg.getData().getString("url");
				String versionId = msg.getData().getString("versionId");
				int mustUpdateStatus = msg.getData().getInt("mustUpdateStatus");
				String imgUrl = msg.getData().getString("imageUrl");
				String versionDesc = msg.getData().getString("versionDesc");
				String appVersion = msg.getData().getString("appVersion");
				if ((DialogUtils.mPopDialog == null || !DialogUtils.mPopDialog
						.isShowing())) {
					// if (mDialog != null) {
					// mDialog.cancel();
					// mDialog = null;
					// }
					if (!TextUtils.isEmpty(url)) {
						if (mustUpdateStatus == 1) {// 1为强制更新
							if (mDialog != null) {
								mDialog.cancel();
								mDialog = null;
							}
							if (mUpdateManager == null)
								mUpdateManager = new UpdateApkManager(
										HomeActivity.this);
							mUpdateManager.checkUpdateInfo(appVersion, imgUrl,
									versionDesc, url, versionId,
									mustUpdateStatus);
							PreferenceUtils.getInstance().setNumForUpdateFalse(
									HomeActivity.this, 0);
						} else if (mustUpdateStatus == 0) {// 0为非强制更新
							if (PreferenceUtils.getInstance()
									.getNumForUpdateFalse(HomeActivity.this) == 1) {
								PreferenceUtils.getInstance()
										.setNumForUpdateFalse(
												HomeActivity.this, -2);
								if (mDialog != null) {
									mDialog.cancel();
									mDialog = null;
								}
								if (mUpdateManager == null)
									mUpdateManager = new UpdateApkManager(
											HomeActivity.this);
								mUpdateManager.checkUpdateInfo(appVersion,
										imgUrl, versionDesc, url, versionId,
										mustUpdateStatus);
							} else if (PreferenceUtils.getInstance()
									.getNumForUpdateFalse(HomeActivity.this) > 1) {
								PreferenceUtils.getInstance()
										.setNumForUpdateFalse(
												HomeActivity.this, 0);
							}
						}
					}
				}
				break;
			// case HAVE_NOTICE:
			// showmDialog(noticeTitle, noticeDesc);
			// break;
			case GET_HOMEPAGE_FAILURE:
				showToast(pageDesc);
				break;
			case GET_ALLCONFIG_SUCCESS:
				setFragmentView(curFragment);
				Regtips regtips = mAllConfig.getRegtips();
				if (tv1 != null && tv2 != null && regtips != null) {
					tv1.setText(regtips.getExtgx());
					tv2.setText(regtips.getExtcoupon());
				}
				if (mAllConfig.getHomeIcon().getStart_up_limit() != null
						&& !TextUtils.isEmpty(mAllConfig.getHomeIcon()
								.getStart_up_limit().getStartUpLimit())) {
					if (ImageLoader
							.getInstance()
							.getDiscCache()
							.get(mAllConfig.getHomeIcon().getStart_up_limit()
									.getStartUpLimit()) == null) {
						try {
							ImageLoader.getInstance().loadImage(
									mAllConfig.getHomeIcon()
											.getStart_up_limit()
											.getStartUpLimit(), null);
						} catch (Exception e) {
							// 啥也不用干，预加载失败就失败吧
						}
					}

				}
				if (!TextUtils.isEmpty(mAllConfig.getHomeIcon().getHomebgUrl())) {
					ImageLoader.getInstance().displayImage(
							mAllConfig.getHomeIcon().getHomebgUrl(),
							home_bg_img);
				}
				cacheImage(regtips);
				break;
			case Const.NOTIFY_GOT_TIYANJIN_FLAG:
				setFragmentView(2);
				showSupriseDialog(msg.obj.toString());
				isShowGuide = false;
				break;
			case Const.NOTIFY_HOME_SIGN:
				homeNavigation();
				mRegularFragment.signIn();
				break;
			case CLICK_DELAY:
				mClickTime0 = 0;
				mClickTime1 = 0;
				mClickTime2 = 0;
				break;
			default:
				break;
			}
		}
	};

	private void splashGotoAnyWhere() {
		String gotoWhere = getIntent().getStringExtra("gotoWhere");
		if (!TextUtils.isEmpty(gotoWhere)) {
			if (gotoWhere.indexOf("http") < 0) {
				if (gotoWhere.indexOf("FindFragment") >= 0) {
					propertyNavigation();
				} else if (gotoWhere.indexOf("WalletFragment") >= 0) {
					walletNavigation();
				} else {
					try {
						ComponentName componet = new ComponentName(
								"com.kkd.kkdapp", gotoWhere);
						Intent intent = new Intent();
						intent.setComponent(componet);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
						// 保证不崩
					}
				}

			} else {
				Intent intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", gotoWhere);
				startActivity(intent);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		mActivity = this;
		mTintManager.setTintColor(0x00000000);
		MobclickAgent.updateOnlineConfig(this);
		AnalyticsConfig.enableEncrypt(true);
		initialize();

		String toMidFlag = "";
		toMidFlag = getIntent().getStringExtra("toMidFlag");
		if ("toMidFlag".equals(toMidFlag)) {
			// manageNavigation();
		}
		mAllConfig = PreferenceUtils.getInstance().getAllConfigData(this);
		NotifyDispatcher.getInstance().registerNotifyHandler(mHandler);
		String accout = this.getIntent().getStringExtra("account");
		LogUtil.e("accout", accout);
		if (!TextUtils.isEmpty(accout) && "yes".equals(accout)) {
			walletNavigation();
		}
		if (navigationFlag == true) {
			requestImpNotice();
		}
		KkdAppInfo appinfo = KkdAppInfo.getKkdAppInfo();
		long curtime = System.currentTimeMillis() / 1000;
		if (appinfo != null && ((curtime - appinfo.backgroundTime) <= 60)) {
			updateApp();
		}
		if (PreferenceUtils.getInstance().getLogin(this) != 0
				&& !PreferenceUtils.getInstance().getLoginSuccess(this)) {
			showDialog();
		}
		splashGotoAnyWhere();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		int toActivity = intent.getIntExtra("toActivity", -1);
		if (toActivity == 1) {
			homeNavigation();
		} else if (toActivity == 2) {
			propertyNavigation();
		} else if (toActivity == 3) {
			walletNavigation();
		}
	}

	/**
	 * getAllConfig:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	private void getAllConfig() {
		// TODO Auto-generated method stub
		KkdHttpMagager.getInstance().getAllConfig(AllConfig.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mAllConfig = (AllConfig) responseBody;
						PreferenceUtils.getInstance().setAllConfigData(
								HomeActivity.this, (AllConfig) responseBody);
						mHandler.sendEmptyMessage(GET_ALLCONFIG_SUCCESS);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						// 获取失败就算了，无所谓~~~
					}
				});
	}

	/*
	 * 我的资产资产接口
	 */
	public void mymanage() {
		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		String[] cat = customerIdAndToken.split("&");
		if (cat == null || cat.length < 2)
			return;
		KkdHttpMagager.getInstance().getManageManager(new HttpCallBack() {

			@Override
			public void onSuccess(int statusCode, Object res) {

				NotifyDispatcher.getInstance().sendNotify("",
						Const.NOTIFY_GOT_MYPROPERTY_SUCCESS_FLAG);
			}

			@Override
			public void onFailure(int statusCode, String responseBody) {

			}
		});
	}

	/**
	 * 初始化控件
	 */
	public void initialize() {
		regular_bt = (LinearLayout) findViewById(R.id.regular_bt);
		regular_img = (ImageView) this.findViewById(R.id.regular_img);
		regular_tv = (TextView) this.findViewById(R.id.regular_tv);
		find_bt = (RelativeLayout) findViewById(R.id.find_bt);
		find_img = (ImageView) this.findViewById(R.id.find_img);
		find_tv = (TextView) this.findViewById(R.id.find_tv);
		wallet_bt = (RelativeLayout) findViewById(R.id.wallet_bt);
		wallet_img = (ImageView) this.findViewById(R.id.wallet_img);
		wallet_tv = (TextView) this.findViewById(R.id.wallet_tv);
		home_bg_img = (ImageView) this.findViewById(R.id.home_bg_img);

		regular_bt.setOnClickListener(this);
		find_bt.setOnClickListener(this);
		wallet_bt.setOnClickListener(this);
		find_dot = (TextView) this.findViewById(R.id.find_dot);
		dot = (TextView) this.findViewById(R.id.dot);
		mRegularFrameLayout = (FrameLayout) findViewById(R.id.regular_frame);
		mCurrentFrameLayout = (FrameLayout) findViewById(R.id.current_frame);
		mFindFrameLayout = (FrameLayout) findViewById(R.id.find_frame);
		mWalletFrameLayout = (FrameLayout) findViewById(R.id.wallet_frame);
		initTextView();
		initFragmentView();
	}

	private void initTextView() {
		textView = new TextView(this);
		textView.setBackgroundResource(R.drawable.bg_back_toast);
		textView.setText(R.string.homeactivity_exit);
		textView.setGravity(Gravity.CENTER);
		textView.setTextSize(16);
		textView.setTextColor(Color.parseColor("#333333"));
	};

	@Override
	protected void onRestart() {
		super.onRestart();
		// Log.e("getDeviceInfo", getDeviceInfo(this));
	}

	public static String getDeviceInfo(Context context) {
		try {
			org.json.JSONObject json = new org.json.JSONObject();
			android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);

			String device_id = tm.getDeviceId();

			android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);

			String mac = wifi.getConnectionInfo().getMacAddress();
			json.put("mac", mac);

			if (TextUtils.isEmpty(device_id)) {
				device_id = mac;
			}

			if (TextUtils.isEmpty(device_id)) {
				device_id = android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
			}

			json.put("device_id", device_id);

			return json.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 主页导航键设置
	 */
	public void homeNavigation() {

		// if (!PreferenceUtils.getInstance().getShowHomePopupwindow(this)) {
		// showDialog();
		// PreferenceUtils.getInstance().setShowHomePopupwindow(this, true);
		// }
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}
		SystemUtils.onEvent("TabBar_v50_Regular", 1);
		setFragmentView(0);
		requestImpNotice();
		if (popDialog != null) {
			popDialog.cancel();
			popDialog = null;
		}
		navigationFlag = true;
	}

	public void showDialog() {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		AllConfig allConfigData = PreferenceUtils.getInstance()
				.getAllConfigData(this);
		mDialog = DialogUtils.redPackage2Dialog(mActivity,
				allConfigData == null ? "" : allConfigData.getRegtips()
						.getReg_reaward_image());
		mDialog.show();
	}

	public void showAssessmentDialog() {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.assessmentDialog(mActivity, "保守型",
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(mActivity,
								KKDWebActivity.class);
						intent.putExtra("url",
								CurUserModel.getMyInfo().survedUrl);
						startActivity(intent);
						mDialog.dismiss();
					}
				});
		mDialog.show();
	}

	public void propertyNavigation() {

		// if (PreferenceUtils.getInstance().getLogin(this) != 0) {
		// Intent intent = new Intent(this, LoginActivity.class);
		// startActivity(intent);
		// } else {
		SystemUtils.onEvent("TabBar_v50_Discovery", 1);
		setFragmentView(1);
		if (popDialog != null) {
			popDialog.cancel();
			popDialog = null;
		}
		KkdHttpMagager.getInstance().reportNewImg("", "find",
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onFailure(int statusCode, String desc) {
						// TODO Auto-generated method stub

					}
				});
		// }
		navigationFlag = false;

	}

	public void walletNavigation() {
		SystemUtils.onEvent("TabBar_v50_Account", 1);
		if (PreferenceUtils.getInstance().getLogin(this) != 0) {
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityForResult(intent, ACCOUT_LOGIN_CODE);
		} else {
			if (mDialog == null || !mDialog.isShowing()) {
				if (!PreferenceUtils.getInstance().getGuide(this)) {
					showPopupWindow();
					PreferenceUtils.getInstance().setGuide(this, true);
				} else if (CurUserModel.getMyInfo() != null
						&& CurUserModel.getMyInfo().isShowedAsses != 0) {
					CurUserModel.getMyInfo().updateIsShowedAsses(0);
					showAssessmentDialog();
				}
				if (isFirstToWallet) {
					isFirstToWallet = false;
					mWalletFragment.requestAnimation();
				}

			}
			setFragmentView(2);
		}
		navigationFlag = false;
	}

	public Dialog popDialog;// 此dialog不用共用

	public void showPopupWindow() {
		if (popDialog != null) {
			popDialog.cancel();
			popDialog = null;
		}
		popDialog = DialogUtils.generatePopDialog(this);
		popDialog.show();

	}

	private int mClickTime0 = 0;
	private int mClickTime1 = 0;
	private int mClickTime2 = 0;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.regular_bt:// 主页
			if (curFragment != 0) {
				homeNavigation();
			} else {
				if (mClickTime0 > 0) {
					mClickTime0 = 0;
					mRegularFragment.ScrollToTop();
				} else {
					mClickTime0++;
				}
				mClickTime1 = 0;
				mClickTime2 = 0;
				mHandler.sendEmptyMessageDelayed(CLICK_DELAY, 500);

			}
			break;
		case R.id.find_bt:// 资产
			if (curFragment != 1) {
				propertyNavigation();
			} else {
				if (mClickTime1 > 0) {
					mClickTime1 = 0;
					mFindFragment.ScrollToTop();
				} else {
					mClickTime1++;
				}
				mClickTime0 = 0;
				mClickTime2 = 0;
				mHandler.sendEmptyMessageDelayed(CLICK_DELAY, 500);
			}

			break;
		case R.id.wallet_bt:// 资产
			if (curFragment != 2) {
				walletNavigation();
			} else {
				if (mClickTime2 > 0) {
					mClickTime2 = 0;
					mWalletFragment.ScrollToTop();
				} else {
					mClickTime2++;
				}
				mClickTime1 = 0;
				mClickTime0 = 0;
				mHandler.sendEmptyMessageDelayed(CLICK_DELAY, 500);
			}
			break;
		}

	}

	@Override
	protected void onDestroy() {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mUpdateManager != null) {
			mUpdateManager.cancle();
		}
		super.onDestroy();
		NotifyDispatcher.getInstance().unRegisterNotifyHandler(mHandler);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (PreferenceUtils.getInstance().getLogin(this) != 0) {
			homeNavigation();
		} else if (PreferenceUtils.getInstance().getLogin(this) == 0) {
			if (requestCode == ACCOUT_LOGIN_CODE && isShowGuide) {
				walletNavigation();
			}
		}

		if (requestCode == 400 && resultCode == 100) { // 安全退出
			showToast2("您已安全退出登录");
		}
		if (requestCode == 400 && resultCode == 101) { // 拿特权
			homeNavigation();
		}
		if (requestCode == 200 && resultCode == 300) {
			homeNavigation();
		}

	}

	public void initFragmentView() {
		FragmentTransaction tran = getSupportFragmentManager()
				.beginTransaction();
		tran.replace(R.id.regular_frame, mRegularFragment);
		// tran.replace(R.id.current_frame, mCurrentFragment);
		tran.replace(R.id.find_frame, mFindFragment);
		tran.replace(R.id.wallet_frame, mWalletFragment);

		tran.commit();
		homeNavigation();
	}

	/**
	 * Fragment切换
	 * 
	 * @param frament
	 */
	public void setFragmentView(int index) {
		curFragment = index;
		mRegularFrameLayout.setVisibility(View.GONE);
		mCurrentFrameLayout.setVisibility(View.GONE);
		mFindFrameLayout.setVisibility(View.GONE);
		mWalletFrameLayout.setVisibility(View.GONE);

		if (mAllConfig != null) {
			ImageLoader.getInstance().displayImage(
					mAllConfig.getHomeIcon().getZhIcon_0(), wallet_img,
					R.drawable.home_tab_icon_wallet_nomal);
			ImageLoader.getInstance().displayImage(
					mAllConfig.getHomeIcon().getDqIcon_0(), regular_img,
					R.drawable.home_tab_icon_regular_nomal);
			ImageLoader.getInstance().displayImage(
					mAllConfig.getHomeIcon().getFxIcon_0(), find_img,
					R.drawable.home_tab_icon_find_nomal);
			int color = Color.parseColor(mAllConfig.getHomeIcon().getUpColor());
			regular_tv.setTextColor(color);
			find_tv.setTextColor(color);
			wallet_tv.setTextColor(color);
		} else {
			wallet_img.setImageResource(R.drawable.home_tab_icon_wallet_nomal);
			regular_img
					.setImageResource(R.drawable.home_tab_icon_regular_nomal);
			find_img.setImageResource(R.drawable.home_tab_icon_find_nomal);
			regular_tv.setTextColor(0xff999999);
			find_tv.setTextColor(0xff999999);
			wallet_tv.setTextColor(0xff999999);
		}

		switch (index) {
		case 0:

			if (mAllConfig != null) {
				ImageLoader.getInstance().displayImage(
						mAllConfig.getHomeIcon().getDqIcon_1(), regular_img,
						R.drawable.home_tab_icon_regular_selected);
				int color = Color.parseColor(mAllConfig.getHomeIcon()
						.getDownColor());
				regular_tv.setTextColor(color);
			} else {
				regular_img
						.setImageResource(R.drawable.home_tab_icon_regular_selected);
				regular_tv.setTextColor(0xff7b8bed);
			}
			mRegularFrameLayout.setVisibility(View.VISIBLE);
			break;
		case 1:
			if (mAllConfig != null) {
				ImageLoader.getInstance().displayImage(
						mAllConfig.getHomeIcon().getFxIcon_1(), find_img,
						R.drawable.home_tab_icon_find_selected);
				int color = Color.parseColor(mAllConfig.getHomeIcon()
						.getDownColor());
				find_tv.setTextColor(color);
			} else {
				find_tv.setTextColor(0xff7b8bed);
				find_img.setImageResource(R.drawable.home_tab_icon_find_selected);
			}
			mFindFrameLayout.setVisibility(View.VISIBLE);
			break;
		case 2:
			if (mAllConfig != null) {
				ImageLoader.getInstance().displayImage(
						mAllConfig.getHomeIcon().getZhIcon_1(), wallet_img,
						R.drawable.home_tab_icon_wallet_selected);
				int color = Color.parseColor(mAllConfig.getHomeIcon()
						.getDownColor());
				wallet_tv.setTextColor(color);
			} else {
				wallet_img
						.setImageResource(R.drawable.home_tab_icon_wallet_selected);
				wallet_tv.setTextColor(0xff7b8bed);
			}
			mWalletFrameLayout.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				// showToast(R.string.homeactivity_exit);
				// Toast.makeText(HomeActivity.this,
				// R.string.homeactivity_exit,
				// Toast.LENGTH_SHORT).show();
				Toast toast = new Toast(HomeActivity.this);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.BOTTOM, 0, 0);
				toast.setView(textView);
				toast.show();
				mExitTime = System.currentTimeMillis();
			} else {
				PreferenceUtils.getInstance().eliminateOneUpdate(this);
				PreferenceUtils.getInstance()
						.setEveryDay(HomeActivity.this, "");
				finish();
				System.exit(0);
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getAllConfig();
		KkdAppInfo appinfo = KkdAppInfo.getKkdAppInfo();
		long curtime = System.currentTimeMillis() / 1000;
		// || !PreferenceUtils.getInstance().getSystemInformation(this)
		// || super.newMsgCount > 0
		// || PreferenceUtils.getInstance().getNewCoin(this)) {
		// dot.setVisibility(View.VISIBLE);
		// } else {
		// dot.setVisibility(View.GONE);
		// }
		if (super.newMsgCount > 0
				|| !PreferenceUtils.getInstance().getSystemInformation(this)) {
			dot.setVisibility(View.VISIBLE);
		} else {
			dot.setVisibility(View.GONE);
		}
		if (PreferenceUtils.getLogin(this) == 0) {
			queryHomePage();
		}
		if (navigationFlag == true) {
			requestImpNotice();
		}
		if (appinfo == null || ((curtime - appinfo.backgroundTime) > 60)) {
			updateApp();
		}
		mymanage();

	}

	/**
	 * 
	 * 版本更新
	 * 
	 */
	public void updateApp() {

		try {
			versionId = getVersionCode();
		} catch (Exception e) {
			e.printStackTrace();
		}
		KkdHttpMagager.getInstance().getUpdateManager(versionId,
				UpdateData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						UpdateData data = (UpdateData) responseBody;
						if (data.getUpdateStatus() == 1) {
							Message msg = new Message();
							msg.what = HAVE_NEW_APP;
							Bundle intent = new Bundle();
							intent.putString("url", data.getUrl());
							intent.putString("versionId", data.getVersionId());
							intent.putInt("mustUpdateStatus",
									data.getMustUpdateStatus());
							intent.putString("imageUrl", data.getImageUrl());
							intent.putString("versionDesc",
									data.getVersionDesc());
							intent.putString("appVersion", data.getAppVersion());
							msg.setData(intent);
							mHandler.sendMessage(msg);
						} else {
							PreferenceUtils.getInstance().setNumForUpdateFalse(
									HomeActivity.this, 0);
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						// upDesc = desc;
						// mHandler.sendEmptyMessage(HAVE_NEW_APP_FAILURE);
						// 失败就算了，下次再说
					}
				});
	}

	// 后台启动时调用HomePage
	public void queryHomePage() {
		User user = CurUserModel.getCurUser();
		if (user != null && user.state == 0) {// 用户不为空且已登陆
			KkdHttpMagager.getInstance().getQueryHomePageManager(
					BaseApplication.getInstance().device_token,
					HomePageData.class, new HttpCallBack() {

						@Override
						public void onSuccess(int statusCode,
								Object responseBody) {
							try {
								HomePageData data = (HomePageData) responseBody;
								int realNameAuth = data.getIsRealNameAuth();
								PreferenceUtils.getInstance().setAutonym(
										HomeActivity.this, realNameAuth);
								int boundBankCard = data.getIsBoundBankCard();
								String userHeadUrl = data.getUserHeadUrl();
								PreferenceUtils.getInstance().setHeadUrl(
										HomeActivity.this, userHeadUrl);
								PreferenceUtils.getInstance().setBoundBankCard(
										HomeActivity.this, boundBankCard);
								PreferenceUtils.getInstance().setOpenAccount(
										HomeActivity.this,
										data.getIsOpenAccount());
								String idCard = data.getIdCard();
								String realName = data.getRealName();
								PreferenceUtils.getInstance()
										.setIdCardAndRealName(
												HomeActivity.this, idCard,
												realName);
								String phone = data.getPhone();
								String friendShareUrl = data
										.getFriendShareUrl();
								PreferenceUtils.getInstance().setTwoDimension(
										HomeActivity.this, friendShareUrl);
								PreferenceUtils.getInstance()
										.setInviteFriendUrl(HomeActivity.this,
												data.getInviteFriendUrl());

								PreferenceUtils.getInstance().setInviteFriend(
										HomeActivity.this,
										data.getInviteFriendShare());
								PreferenceUtils.getInstance().setPhone(
										HomeActivity.this, phone);
								int isPayPassword = data.getIsPayPassword();
								PreferenceUtils.getInstance()
										.setWithdrawPassWord(HomeActivity.this,
												isPayPassword);
								PreferenceUtils.getInstance().setHomePageData(
										HomeActivity.this, data);
								List<HomePageDataList> cardList = data
										.getCardList();
								newMsgCount = data.getNewMsgCount();
								if (cardList.size() != 0) {
									String cardId = cardList.get(0).getCardId();
									User.updateCardId(cardId);
									PreferenceUtils.getInstance().setCardNo(
											HomeActivity.this,
											cardList.get(0).getCardNo());

								}
								// 新浪UID
								String sinaUid = data.getSinaUid();
								PreferenceUtils.getInstance().setSinaUid(
										HomeActivity.this, sinaUid);
								// 用户昵称
								String nickname = data.getNickname();
								PreferenceUtils.getInstance().setNickname(
										HomeActivity.this, nickname);
							} catch (Exception e) {

							}
						}

						@Override
						public void onFailure(int statusCode, String desc) {
							pageDesc = desc;
							mHandler.sendEmptyMessage(GET_HOMEPAGE_FAILURE);
						}
					});
		}

	}

	// public void showDialog() {
	// if (mDialog != null) {
	// mDialog.cancel();
	// mDialog = null;
	// }
	// mDialog = DialogUtil.getMyDialog(this);
	// mDialog.show();
	// }

	/***
	 * 
	 * @Name 首页公告Dialog
	 * 
	 * @param title
	 * 
	 * @param desc
	 */
	public void showmDialog(final String title, final String desc) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}

		mDialog = DialogUtils.getHomeNoticeDialog(this, title, desc,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.close:
							mDialog.dismiss();
							mDialog = null;
							updateApp();
							break;
						}
					}
				});
		mDialog.show();
	}

	// public void showPopupWindow() {
	// if (mDialog != null) {
	// mDialog.cancel();
	// mDialog = null;
	// }
	// mDialog = DialogUtil.generatePopDialog(this);
	// mDialog.show();
	//
	// }

	// 首页公告
	public void requestImpNotice() {
		KkdHttpMagager.getInstance().getImpNotice(HomePageNotice.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						HomePageNotice mHomePageNotice = (HomePageNotice) responseBody;
						Notice.insertNotices(mHomePageNotice.getDataList());
						NotifyDispatcher.getInstance().sendNotify("",
								Const.NOTIFY_HAVE_NOTICE);
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}

	public boolean isMovingSpecialActivityImg = false;

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (isMovingSpecialActivityImg) {
			return mRegularFragment.onMovingSpecialActivityImg(event);
		} else {
			return super.dispatchTouchEvent(event);
		}

	}

	public void showSupriseDialog(String url) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}

		mDialog = DialogUtils.forTenderSupriseDialog(this, url,
				new OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						mWalletFragment.showExperienceCountAnimation();
						if (!PreferenceUtils.getInstance().getGuide(
								HomeActivity.this)) {
							showPopupWindow();
							PreferenceUtils.getInstance().setGuide(
									HomeActivity.this, true);
						}

						if (isFirstToWallet) {
							isFirstToWallet = false;
							mWalletFragment.requestAnimation();
						}

						isShowGuide = true;
					}
				});
	}

	private void cacheImage(Regtips regtips) {
		if (iv_reg_reaward_image_forCache == null) {
			iv_reg_reaward_image_forCache = new ImageView(mActivity);
			iv_reg_reaward_image_forCache.setLayoutParams(new LayoutParams(10,
					10));
		}
		if (iv_poi_pre_reward_image_forCache == null) {
			iv_poi_pre_reward_image_forCache = new ImageView(mActivity);
			iv_poi_pre_reward_image_forCache.setLayoutParams(new LayoutParams(
					10, 10));
		}
		if (iv_poi_pre_reward_image2_forCache == null) {
			iv_poi_pre_reward_image2_forCache = new ImageView(mActivity);
			iv_poi_pre_reward_image2_forCache.setLayoutParams(new LayoutParams(
					10, 10));
		}
		if (iv_regSuccessImage_forCache == null) {
			iv_regSuccessImage_forCache = new ImageView(mActivity);
			iv_regSuccessImage_forCache
					.setLayoutParams(new LayoutParams(10, 10));
		}
		if (iv_mis_succ_image_forCache == null) {
			iv_mis_succ_image_forCache = new ImageView(mActivity);
			iv_mis_succ_image_forCache
					.setLayoutParams(new LayoutParams(10, 10));
		}
		ImageLoader.getInstance().displayImage(regtips.getReg_reaward_image(),
				iv_reg_reaward_image_forCache);
		ImageLoader.getInstance().displayImage(
				regtips.getPoi_pre_reward_image(),
				iv_poi_pre_reward_image_forCache);
		ImageLoader.getInstance().displayImage(
				regtips.getPoi_pre_reward_image2(),
				iv_poi_pre_reward_image2_forCache);
		ImageLoader.getInstance().displayImage(regtips.getRegSuccessImage(),
				iv_regSuccessImage_forCache);
		ImageLoader.getInstance().displayImage(regtips.getMis_succ_image(),
				iv_mis_succ_image_forCache);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// super.onSaveInstanceState(outState);
	}

	public void checkRedpackage() {
		if (PreferenceUtils.getInstance().getLogin(this) != 0
				&& !PreferenceUtils.getInstance().getLoginSuccess(this)) {
			showDialog();
		}
	}
}
